package com.hl.card.pay.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.persistence.model.Recharge;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.util.ResponseModel;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.modular.pack.service.RechargeService;
import com.hl.card.modular.pack.service.TokenWallet;
import com.hl.card.modular.pack.service.UserDataService;
import com.hl.card.modular.system.service.ISysDicService;
import com.hl.card.pay.dto.CollectDto;
import com.hl.card.pay.service.CollectService;
import com.hl.card.pay.service.CommonService;
import com.hl.card.pay.vo.CollectVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 提币
 */
@Controller
public class CollectController {
    @Autowired
    private UserDataService userDataService;
    @Autowired
    ISysDicService sysDicService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private CommonService commonService;

    @Autowired
    private RechargeService rechargeService;

    @RequestMapping("collectTest")
    public String collectTest() {
        return "/collect/collectTest.html";
    }

    @RequestMapping("collect")
    public String collect(CollectDto collectDto) {
        return "/collect/collectTest.html";
    }

    @RequestMapping("doCollect")
    public String doCollect(CollectDto collectDto) {
        return "/collect/payResult.html";
    }

    @RequestMapping("doCollectApi")
    @ResponseBody
    public ResponseModel doCollect(CollectVo collectVo) {
        int times = commonService.findPayError(collectVo.getUserId());//支付密码错误次数
        ResponseModel responseModel = getLimit(collectVo.getUserId(), collectVo.getCurrency());
        Map balance = (Map) responseModel.getData();
        if("0000".equals(responseModel.getStatus())) {
            int temp = (int) balance.get("balance");
            if(temp < Integer.parseInt(collectVo.getAmount())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "金额大于可提金额，请勿非法操作");
                jsonObject.put("errorTimes", times);
                responseModel.setStatus("0003");
                responseModel.setData(jsonObject);
                return responseModel;
            }
        }
        responseModel = new ResponseModel();
        boolean b = commonService.checkPayPassWord(collectVo.getUserId(), collectVo.getPayPassWord());//验证支付密码
        if (times > 4) {
            responseModel.setStatus("0001");
            responseModel.setData("密码输错次数超过上限！明天再试");
            return responseModel;
        }
        if (b) {
            int poundage = (int) balance.get("poundage");
            collectVo.setParam1(Integer.toString(poundage));
            String result = collectService.doCollect(collectVo);
            responseModel.setStatus("0000");
            responseModel.setData(JSONObject.parseObject(result));
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "交易密码错误");
            jsonObject.put("errorTimes", times + 1);
            responseModel.setStatus("0002");
            responseModel.setData(jsonObject);
        }
        return responseModel;
    }
    @RequestMapping("confirmCollectApi")
    @ResponseBody
    public ResponseModel confirmCollectApi(@RequestParam String orderNo) {
        ResponseModel responseModel = new ResponseModel();
        CollectDto  collectDto=new CollectDto();
        collectDto.setMchTransNo(orderNo);
        JSONObject result = collectService.doTrans(collectDto);
        System.out.println("retStr"+result.toJSONString());
        if(result.get("resCode").equals("SUCCESS")){
            responseModel.setStatus("0000");
            responseModel.setData(result);
            return responseModel;
        }
        responseModel.setStatus("0003");
        responseModel.setData(result);
        return responseModel;
    }

    @RequestMapping("collectList")
    @ResponseBody
    public ResponseModel CollectList(CollectVo collectVo, int size, int current) {
        ResponseModel responseModel = new ResponseModel();
        Recharge recharge = new Recharge();
        recharge.setUser_id(collectVo.getUserId());
        recharge.setExtra("WITHDRAW");
        Page<Recharge> dPage = rechargeService.selectMultiConditionLimit(recharge, size, current);
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("total", dPage.getTotal());
        jsonMap.put("rows", dPage.getRecords());
        jsonMap.put("current", dPage.getCurrent());
        jsonMap.put("pages", dPage.getPages());
        responseModel.setStatus("0000");
        responseModel.setData(dPage);
        responseModel.setStatus("0000");
        responseModel.setData(jsonMap);
        return responseModel;
    }
    @RequestMapping("/collect/getBalance")
    @ResponseBody
    public ResponseModel getBalance(String userId, String currency) {
        ResponseModel responseModel = new ResponseModel();
        int blance = collectService.getBalance(userId, currency);
        responseModel.setData(blance);
        responseModel.setStatus("0000");
        return responseModel;
    }

    @RequestMapping("/collect/getLimit")
    @ResponseBody
    public ResponseModel getLimit(String userId , String currency) {
        ResponseModel responseModel = new ResponseModel();
        String limit = "5000";
        Map map = new HashMap<>();
        Map<String, Object> poundageMap = sysDicService.selectListByCodeNo("TBSXF", currency);
        Map<String, Object> commonItemMax = sysDicService.selectListByCodeNo("TZTBXZ", "PER_ORDER_MAX");
        Map<String, Object> commonItemMin = sysDicService.selectListByCodeNo("TZTBXZ", "PER_ORDER_MIN");
        Map<String, Object> communityItemMin = sysDicService.selectListByCodeNo("TZTBXZ", "COMMUNITY_PER_ORDER_MIN");
        Map<String, Object> min;
        int commonLimtMin=-1, communityLimitMin=5000;
        Wrapper<User> wrapperuser = new EntityWrapper<User>();
        wrapperuser.eq("user_id", userId);
        User parentUser = userDataService.selectOne(wrapperuser);
        if(parentUser == null) {
            responseModel.setData("用户不存在");
            responseModel.setStatus("0001");
            return responseModel;
        }
        map.put("msg", "");
        String iscommunityUser=parentUser.getIscommunityUser();
        if(iscommunityUser!=null&&iscommunityUser.equals("1")){//是群主
            map.put("msg", "社区管理员单笔提币数量不能低于5000HTL");
            if(communityItemMin != null)
            {
                limit = (String)communityItemMin.get("dicValue");
                if(StringUtils.isBlank(limit)) {
                    limit = "-1";
                }
                communityLimitMin = Integer.parseInt(limit);
            }
        }else {
            limit = (String)commonItemMin.get("dicValue");
            communityLimitMin = -1;
        }
        if(commonItemMin != null)
        {
            limit = (String)commonItemMin.get("dicValue");
            if(StringUtils.isBlank(limit)) {
                limit = "-1";
            }
            commonLimtMin = Integer.parseInt(limit);
        }

        int minLimit;
        if(communityLimitMin > commonLimtMin) {
            minLimit = communityLimitMin;
        }else {
            minLimit = commonLimtMin;
        }

        if(commonItemMax != null) {
            limit = (String)commonItemMax.get("dicValue");
            if(StringUtils.isBlank(limit)) {
                limit = "5000";
            }
        }

        int maxLimit = Integer.parseInt(limit);
        //减去手续费
        int poundage;
        if(poundageMap != null) {
            poundage = Integer.parseInt((String) poundageMap.get("dicValue"));
        }else {
            if("eth".equalsIgnoreCase(currency)) {
                //poundage = 0.0003;
                poundage = 3;//这里的单位是wei
            }else {
                poundage = 5;
            }
        }
        int balance = collectService.getBalanceAll(userId, currency);
        balance = (balance - poundage)/100*100;

        if(maxLimit != -1 && maxLimit < balance){
            balance = maxLimit;
        }

        if(minLimit != -1 && minLimit > balance) {
            balance = 0;
        }
        map.put("max", maxLimit);
        map.put("min", minLimit);
        map.put("balance", balance);
        map.put("poundage", poundage);
        responseModel.setData(map);
        responseModel.setStatus("0000");
        return responseModel;
    }
}
